const _ = require('lodash')

const { clean } = require('../../core/common')
const BaseManager = require('../base/base-manager')
const { writeJSONFileSync, readJSONFileSync } = require('../../core/utils')
const { USER_SETTINGS_FILE_PATH } = require('../../core/variable')

class SaveDataMgr extends BaseManager {
  constructor(gameName) {
    super(gameName)
  }

  /**
   * 通过远程 Git 仓库拉取游戏存档
   *
   * @param {boolean} init - 是否为初始化拉取，默认为 false
   * @returns 无返回值
   */
  pull(init = false) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve) => {
      const { simpleGit } = await import('simple-git')

      if (init) {
        await simpleGit().clone(this.repoPath, this.saveDataDir)

        resolve()
        return
      }

      const repo = simpleGit(this.saveDataDir)
      await repo.pull()

      resolve()
    })
  }

  /**
   * 重置 Git 仓库
   *
   * 使用 simple-git 库，将当前仓库重置到上一次提交的状态
   */
  reset() {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve) => {
      const { simpleGit } = await import('simple-git')

      const repo = simpleGit(this.saveDataDir)
      await repo.reset(['--hard'])

      resolve()
    })
  }

  /**
   * 推送更改到远程仓库
   *
   * @param commitMsg 提交信息，默认为游戏名称和当前时间的字符串
   */
  push(commitMsg = '') {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve) => {
      commitMsg =
        commitMsg || `【${this.gameName}】${new Date().toLocaleString()}`

      const { simpleGit } = await import('simple-git')

      const repo = simpleGit(this.saveDataDir)
      await repo.add('./*')
      await repo.commit(commitMsg)
      await repo.push('origin', 'master')
      // await repo.push('gitee', 'master')

      resolve()
    })
  }

  /**
   * 添加或更新游戏设置
   *
   * @param {Object} params - 包含游戏设置信息的对象
   * @param {string} params.gameName - 游戏名称
   * @param {string} params.repoPath - 游戏存档 Git 仓库路径
   * @param {string} params.dirName - 游戏存档目录名称
   * @param {string[]} params.dirs - 其他需要清理的目录数组（可选）
   */
  static addOrUpdateSettings({ gameName, repoPath, dirName, dirs = [] }) {
    return new Promise((resolve, reject) => {
      if (!gameName) {
        return reject(`No game name provided.`)
      }

      const settings = require('../../../settings')
      const newSettings = _.merge(settings, {
        [gameName]: clean({
          repoPath,
          dirName,
          dirs
        })
      })

      // 更新 JSON 文件
      writeJSONFileSync(USER_SETTINGS_FILE_PATH, newSettings)

      resolve(`Updated settings for game ${gameName}`)
    })
  }

  static clearSettings(gameName = '') {
    const settings = require('../../../settings')

    let newSettings = gameName ? _.omit(settings, [gameName]) : {}
    writeJSONFileSync(USER_SETTINGS_FILE_PATH, newSettings)

    return readJSONFileSync(USER_SETTINGS_FILE_PATH)
  }

  static openSettingsFile() {
    const { openFile } = require('../../core/utils')
    openFile(USER_SETTINGS_FILE_PATH)
  }
}

module.exports = SaveDataMgr
